package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.server.intercepror.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class CommentsService {

    @DubboReference
    private CommentApi commentApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    //分页查询指定动态的评论
    public PageResult findComments(String movementId, Integer page, Integer pagesize) {
        Integer commentType = 2;//互动类型：评论
        //调用API查询评论数据  List<Comment>
        List<Comment>  list = commentApi.findComments(movementId,commentType,page,pagesize);
        //判断评论列表是否存在，返回空
        if(CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        //提取所有发布人的id
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds);
        //查询所有发布人信息
        //循环List<Comment>，一个Comment构造一个Vo
        List<CommentVo> vos = new ArrayList<>();
        for (Comment comment : list) {
            //获取评论人的用户id
            Long userId = comment.getUserId();
            //调用api查询用户信息
            UserInfo userInfo = map.get(userId);
            CommentVo vo = CommentVo.init(userInfo, comment);
            vos.add(vo);
        }
        //返回
        return new PageResult(page,pagesize,0l,vos);
    }

    //发布评论
    public void saveComment(String movementId, String content) {
        //构造Comment对象
        Integer commentType = 2;
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(commentType);
        comment.setContent(content);
        comment.setUserId(UserHolder.getUserId());
        comment.setCreated(System.currentTimeMillis());
        //调用api保存评论数据，返回评论总数量
        Integer count = commentApi.save(comment);
        System.out.println("count="+count);
    }
}
